package com.example.androidfinalproject.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SearchView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.androidfinalproject.R;
import com.example.androidfinalproject.adapter.DataItemAdapter;
import com.example.androidfinalproject.entity.DataItem;
import com.example.androidfinalproject.global.Global;
import com.example.androidfinalproject.utils.SerializeUtil;
import com.example.androidfinalproject.utils.StorageUtil;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class DataListActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private DataItemAdapter dataItemAdapter;
    private RecyclerView.LayoutManager layoutManager;
    private List<DataItem> dataItemList = new ArrayList<>();
    private FloatingActionButton post;
    private DrawerLayout drawerLayout;
    private List<DataItem> myPost = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_list);

        // 顶部菜单
        final Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setLogo(R.drawable.icons8_cat_100);
        toolbar.setTitle("");
        toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
        setSupportActionBar(toolbar);
        toolbar.setLongClickable(true);
        final boolean[] small = {true};
        toolbar.setOnLongClickListener(
                new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        if (small[0]) {
                            toolbar.setLogo(R.drawable.icons8_cat_100__2_);
                        } else {
                            toolbar.setLogo(R.drawable.icons8_cat_100);
                        }
                        small[0] = !small[0];
                        return false;
                    }
                });

        //        toolbar.setNavigationOnClickListener(
        //                new View.OnClickListener() {
        //                    @Override
        //                    public void onClick(View v) {
        //                        TextView username = findViewById(R.id.username1);
        //                        username.setText(Global.getCurUserName());
        //                        drawerLayout.openDrawer(GravityCompat.START);
        //                    }
        //                });

        // 侧边栏菜单
        drawerLayout = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.navigation);
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                        switch (item.getItemId()) {
                            case R.id.personal_homepage: // 个人主页
                                Intent intent1 =
                                        new Intent(DataListActivity.this, HomePageActivity.class);
                                startActivityForResult(intent1, 2);
                                break;
                            case R.id.my_collections: // 我的收藏
                                Intent intent2 =
                                        new Intent(
                                                DataListActivity.this, MyCollectionActivity.class);
                                startActivityForResult(intent2, 2);
                                break;
                            case R.id.log_out: // 注销
                                Toast.makeText(DataListActivity.this, "注销成功！", Toast.LENGTH_SHORT)
                                        .show();
                                finish();
                                break;
                            default:
                                break;
                        }
                        return true;
                    }
                });

        recyclerView = findViewById(R.id.recyclerview);
        post = findViewById(R.id.floatingActionButton);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        // 添加Android自带的分割线
        recyclerView.addItemDecoration(
                new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        initDataItems();
        dataItemAdapter =
                new DataItemAdapter(dataItemList, getApplicationContext(), getCacheDir(), 0);
        recyclerView.setAdapter(dataItemAdapter);

        // 点击发布按钮
        post.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(DataListActivity.this, PostActivity.class);
                        startActivityForResult(intent, 1);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                Bundle bundle = data.getExtras();
                int n = dataItemList.size();
                // 反序列化得到新的item
                DataItem newItem =
                        (DataItem) SerializeUtil.deserialize(bundle.getByteArray("data"));
                dataItemList.add(newItem);
                myPost.add(newItem);
                dataItemAdapter.notifyItemInserted(n);
                recyclerView.scrollToPosition(n);
                Toast.makeText(getApplicationContext(), "发布成功！", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == 2) {
            dataItemList = Global.getDataItemList();
            dataItemAdapter.notifyDataSetChanged();
        }
    }

    /** 随机初始化一些数据 */
    @SuppressLint("NewApi")
    private void initDataItems() {
        String[] titles = getResources().getStringArray(R.array.title_list);
        String[] phones = getResources().getStringArray(R.array.phone_list);
        String[] urls = getResources().getStringArray(R.array.picurl_list);
        String[] details = getResources().getStringArray(R.array.detail_list);
        String fileName;
        for (int i = 0; i < titles.length; i++) {
            fileName = UUID.randomUUID().toString();
            StorageUtil.downloadImage(getCacheDir(), fileName, urls[i]);
            dataItemList.add(
                    new DataItem(
                            "admin",
                            titles[i],
                            details[i],
                            fileName,
                            LocalDate.now().toString(),
                            Math.random() * 100,
                            phones[i]));
        }
        Global.setDataItemList(dataItemList);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu, menu);

        MenuItem searchItem = menu.findItem(R.id.search_action);
        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setOnQueryTextListener(
                new SearchView.OnQueryTextListener() {
                    @Override
                    public boolean onQueryTextSubmit(String query) {
                        query = query.trim();
                        for (int i = 0; i < dataItemList.size(); ++i) {
                            if (dataItemList.get(i).getTitle().contains(query)) {
                                recyclerView.scrollToPosition(i);
                                return true;
                            }
                        }
                        Toast.makeText(
                                        getApplicationContext(),
                                        "对不起，没有找到您需要的二手物品相关帖。",
                                        Toast.LENGTH_SHORT)
                                .show();
                        return false;
                    }

                    @Override
                    public boolean onQueryTextChange(String newText) {
                        return false;
                    }
                });
        return super.onCreateOptionsMenu(menu);
    }
}
